package com.atguigu.spzx.manager.service.impl;

import com.atguigu.spzx.common.log.annotation.Log;
import com.atguigu.spzx.manager.mapper.SysRoleUserMapper;
import com.atguigu.spzx.manager.service.SysRoleUserService;
import com.atguigu.spzx.model.dto.system.AssignRoleDto;
import com.atguigu.spzx.model.entity.system.SysRoleUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
@Transactional
public class SysRoleUserServiceImpl implements SysRoleUserService {

    @Autowired
    SysRoleUserMapper sysRoleUserMapper;

    @Log(title = "用户分配角色",businessType = 2)
    @Transactional
    @Override
    public void doAssign(AssignRoleDto assginRoleDto) {
        //1.由于分配时需要考虑，哪些角色不动，哪些新增，哪些去掉。怪麻烦的。所以采用直接有效的暴力开发方式。

        //删除一批旧关系数据
        sysRoleUserMapper.deleteRelationship(assginRoleDto.getUserId());


        //int i = 1/0; //抛运行期异常。 事务回滚策略：遇到运行期异常RuntimeException自动回滚。遇到编译期异常不回滚。

        //保存一批新的关系数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        if(!CollectionUtils.isEmpty(roleIdList)){
            for (Long roleId : roleIdList) {
                SysRoleUser sysRoleUser = new SysRoleUser();
                sysRoleUser.setUserId(assginRoleDto.getUserId());
                sysRoleUser.setRoleId(roleId);
                sysRoleUserMapper.insert(sysRoleUser);
            }
        }
    }
}
